package org.minbox.chapter.service;

import com.alibaba.fastjson.JSON;
import org.minbox.chapter.entity.SystemUser;
import org.minbox.chapter.mapper.SystemUserEnhanceMapper;
import org.minbox.framework.api.boot.plugin.security.delegate.ApiBootStoreDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 自定义读取用户信息
 *
 * @author 恒宇少年
 */
@Service
public class UserService implements ApiBootStoreDelegate {
    /**
     * logger instance
     */
    static Logger logger = LoggerFactory.getLogger(UserService.class);
    /**
     * 用户数据接口
     */
    @Autowired
    private SystemUserEnhanceMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails = mapper.findByLoginName(username);
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new UsernameNotFoundException("用户：" + username + "，不存在.");
        }
        logger.info("登录用户的信息：{}", JSON.toJSONString(userDetails));
        return userDetails;
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param phone {@link SystemUser#getPhone()}
     * @return {@link SystemUser}
     */
    public SystemUser findByPhone(String phone) {
        return mapper.findByPhone(phone);
    }
}
